package cn.clx.ymcc.consumer;

import cn.clx.ymcc.domain.CourseOrder;
import cn.clx.ymcc.dto.PayNotifyDto;
import cn.clx.ymcc.service.ICourseOrderItemService;
import cn.clx.ymcc.service.ICourseOrderService;
import cn.clx.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;

/**
 *  pay微服务，成功支付，消费消息修改Order订单状态
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "pay-success-topic",
        selectorExpression="course-order-saveorupdate-tags"	//tags
                ,consumerGroup = "service-pay-to-order-consumer",
        messageModel = MessageModel.BROADCASTING)
public class OrderUpdateMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    /**
     * 需保证消费的幂等性
     * @param message
     */
    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        log.info("支付宝异步回调mq，修改订单状态");
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        PayNotifyDto payNotifyDto = JSONObject.parseObject(msg, PayNotifyDto.class);
        String extParams = payNotifyDto.getExtParams();
        String[] split = extParams.split(":");
        String userid = split[0];
        String courseId = split[1];
        CourseOrder order = courseOrderService.findOrderByOrderNo(payNotifyDto.getOrderNo());
        AssertUtil.isNotNull(order,"该订单不存在");
        boolean IsOK = order.getStatusOrder() == CourseOrder.STATE_WAIT_PAY;
        AssertUtil.isTrue(IsOK,"订单状态不对");
        order.setStatusOrder(CourseOrder.STATE_PAY_SUCCESS);
        courseOrderService.updateById(order);
    }
}